package com.pro01.apirednote.controller;

import com.pro01.apirednote.pojo.Result;
import com.pro01.apirednote.service.ContentService;
import com.pro01.apirednote.utils.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Set;

@RestController
@RequestMapping("/admin/contents")
@RequiredArgsConstructor
@Slf4j
public class AdminContentController {

    private final ContentService contentService;
    private final RedisTemplate<String, Object> redisTemplate;
    
    private static final String CONTENT_CACHE_PREFIX = "content:";

    // 管理员删除内容
    @DeleteMapping("/{contentId}")
    public Result<Void> deleteContent(@PathVariable Long contentId, HttpServletRequest request) {
        String role = TokenUtil.getRole(request);
        return contentService.adminDeleteContent(contentId, role);
    }
    
    /**
     * 清除内容缓存
     * @param contentId 内容ID，如果为null则清除所有内容缓存
     * @param request HTTP请求
     * @return 操作结果
     */
    @PostMapping("/cache/clear")
    public Result<String> clearContentCache(@RequestParam(required = false) Long contentId, 
                                          HttpServletRequest request) {
        // 权限检查
        String role = TokenUtil.getRole(request);
        if (!"ADMIN".equals(role)) {
            return Result.error("无权限操作");
        }
        
        try {
            if (contentId != null) {
                // 清除特定内容的缓存
                String detailCacheKey = "content:detail:" + contentId;
                String filesCacheKey = "content:files:" + contentId;
                
                boolean detailDeleted = Boolean.TRUE.equals(redisTemplate.delete(detailCacheKey));
                boolean filesDeleted = Boolean.TRUE.equals(redisTemplate.delete(filesCacheKey));
                
                if (detailDeleted || filesDeleted) {
                    log.info("已清除内容缓存，contentId: {}", contentId);
                    return Result.success("已清除指定内容的缓存");
                } else {
                    return Result.success("未找到指定内容的缓存");
                }
            } else {
                // 清除所有内容缓存
                Set<String> keys = redisTemplate.keys(CONTENT_CACHE_PREFIX + "*");
                if (keys != null && !keys.isEmpty()) {
                    redisTemplate.delete(keys);
                    log.info("已清除所有内容缓存，共{}条", keys.size());
                    return Result.success("已清除所有内容缓存，共" + keys.size() + "条");
                } else {
                    return Result.success("未找到内容缓存");
                }
            }
        } catch (Exception e) {
            log.error("清除内容缓存失败", e);
            return Result.error("清除缓存失败: " + e.getMessage());
        }
    }
}